//@ts-nocheck
import React, { useState, useEffect, useRef, useImperativeHandle } from 'react'
// import { HeatMap as AntHeatMap } from '@ant-design/maps'
import HeatImage from './heatimage'

import './index.less'
import { ColorGradientName, HeatData } from './types'

export interface ChartsInstance {
  getInstance?: () => any
}
interface IProps {
  /**
   * 容器宽度
   */
  width?: number
  /**
   * 图片数据
   */
  image: { src: string; width: number; height: number }
  /**
   * 热力数据，受控
   */
  data: Array<{ id: number; xOffset: number; yOffset: number; height: number; width: number }>

  chartRef?: React.MutableRefObject<ChartsInstance>

  id: string
}

// const Config = {
//   step: 100 // 步长
// }

let heatMap: any = {}

const HeatMap: React.FC<IProps> = ({ image, data, width, id, chartRef }) => {
  const heatRef = useRef(null)

  const [mapData, setMapData] = useState([])

  useImperativeHandle(chartRef, () => ({
    getInstance: () => {
      return {
        getDataURL: () => {
          return heatMap[id].getDataUrl()
        }
      }
    }
  }))

  useEffect(() => {
    if (heatMap[id]) heatMap[id].updateData([...formatData(data)])
  }, [data])

  const initHeatimage = () => {
    let element: any = heatRef.current
    let heatOptions = {
      heatValue: 0.05,
      // heatRadius: 15,
      heatBlur: 25,
      colorGradient: 'Incandescent' as ColorGradientName,
      exporting: false,
      // edit: false,
      keys: false,
      displayCanvas: true,
      defaultData: [...formatData(data)]
    }
    if (heatRef.current.nextElementSibling)
      heatRef.current.parentNode.removeChild(heatRef.current.nextElementSibling)
    heatMap[id] = new HeatImage(element, heatOptions)
  }

  const formatData = (data): HeatData[] => {
    return data.map((item) => {
      return {
        x: item.xOffset + item.width / 2,
        y: item.yOffset + item.height / 2,
        width: item.width,
        height: item.height,
        value: 0.25
      }
    })
  }

  return (
    <div
      className="heat-map-container"
      style={{ width, height: (((image.height * 1000) / image.width) * width) / 1000 }}
    >
      <div
        className="heat-map-wrapper"
        style={{
          width: image.width,
          height: image.height,
          transform: `scale(${width / image.width})`
        }}
      >
        <img
          src={image.src}
          style={{ width: image.width, height: image.height }}
          crossOrigin="anonymous"
          ref={heatRef}
          onLoad={() => {
            initHeatimage()
          }}
          alt=""
        />
      </div>
    </div>
  )
}
export default (HeatMap)
